package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.constVo.CredentialConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.CredentialItemDao;
import com.zhangtai.modules.dto.CredentialHangDto;
import com.zhangtai.modules.dto.CredentialInfoDto;
import com.zhangtai.modules.dto.CredentialItemDto;
import com.zhangtai.modules.entity.credential.CredentialHangEntity;
import com.zhangtai.modules.entity.credential.CredentialInfoEntity;
import com.zhangtai.modules.entity.credential.CredentialItemEntity;
import com.zhangtai.modules.service.credential.CredentialHangService;
import com.zhangtai.modules.service.credential.CredentialInfoService;
import com.zhangtai.modules.service.credential.CredentialItemService;
import com.zhangtai.modules.vo.CredentialCheckVo;
import com.zhangtai.modules.vo.CredentialInfoVo;
import com.zhangtai.modules.vo.CredentialListVo;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import com.zhangtai.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags="资质管理")
@RequestMapping("/credential")
@Slf4j
public class CredentialController {

    @Autowired
    private LoginController loginController;
    @Autowired
    private CredentialInfoService credentialInfoService;
    @Autowired
    private CredentialHangService credentialHangService;
    @Autowired
    private CredentialItemService credentialItemService;
    @Autowired
    private CredentialItemDao credentialItemDao;
    @Autowired
    private JobController jobController;

    @PostMapping("/getCredentialList")
    @ApiOperation("资质列表")
    public R<PageResult<CredentialInfoDto>> getCredentialList(@RequestBody @Valid CredentialListVo vo, HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult<CredentialInfoDto> result = credentialInfoService.getCredentialList(vo.getName(),vo.getStatus(),orgIds,vo.getPageNum(),vo.getPageSize());
        List<CredentialInfoDto> list = result.getList();
        if(!CollectionUtils.isEmpty(list)){
            for(CredentialInfoDto dto:list){
                dto.setJobName(jobController.jobMap.get(dto.getJobId()));
                dto.setOrgName(jobController.orgMap.get(dto.getOrgId()));
                dto.setUnitName(jobController.orgMap.get(dto.getUnitId1()));
            }
        }
        return R.ok(result);
    }

    @PostMapping("/getHangList")
    @ApiOperation("挂证列表")
    public R<PageResult<CredentialHangDto>> getHangList(@RequestBody @Valid CredentialListVo vo, HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);


        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult<CredentialHangDto> result = credentialHangService.getHanglList(vo.getName(),vo.getStatus(),orgIds,vo.getPageNum(),vo.getPageSize());
        return R.ok(result);
    }

    @ApiOperation("删除员工资质信息")
    @DeleteMapping("/deleteCredential")
    @SysAuthorityLog(value = "删除员工资质信息")
    @Transactional
    public R deleteCredential(String id){
        if(StringUtils.isEmpty(id)){
            return R.error("资质id为空");
        }
        credentialInfoService.removeOneById(Long.parseLong(id));
        return R.ok();
    }

    @PostMapping("/checkCredential")
    @ApiOperation("通过/拒绝资质审核")
    @SysAuthorityLog(value = "通过/拒绝资质审核")
    @Transactional
    public R checkCredential(@RequestBody @Valid CredentialCheckVo vo){
       CredentialInfoEntity infoEntity = BeanUtilsMabach.doToDto(vo,CredentialInfoEntity.class);
       infoEntity.setId(Long.parseLong(vo.getId()));
       credentialInfoService.updateByIdE(infoEntity);
        return R.ok();
    }

    @PostMapping("/checkCredentialHang")
    @ApiOperation("通过/拒绝挂证审核")
    @SysAuthorityLog(value = "通过/拒绝挂证审核")
    @Transactional
    public R checkCredentialHang(@RequestBody @Valid CredentialCheckVo vo,HttpServletRequest request)throws Exception{
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        CredentialHangEntity infoEntity = BeanUtilsMabach.doToDto(vo,CredentialHangEntity.class);
        CredentialHangEntity oldInfoEntity = credentialHangService.getByIdE(Long.parseLong(vo.getId()));
        if(ObjectUtils.isEmpty(oldInfoEntity)){
            return R.error("挂靠信息不存在，无法审核");
        }
        CredentialInfoEntity entity = credentialInfoService.getByIdE(oldInfoEntity.getCredentialId());
        if(ObjectUtils.isEmpty(entity)){
            return R.error("资质信息已被删除无法挂靠");
        }

        if(vo.getStatus().equals(CredentialConst.HANG_STATUS_CHECKED)){
            entity.setHangStatus(CredentialConst.HANG_STATUS_CHECKED);
        }else{
            entity.setHangStatus(CredentialConst.HANG_STATUS_REFUSE);
        }
        infoEntity.setApplierCode(userInfo.getString("usercode"));
        credentialInfoService.updateByIdE(entity);
        infoEntity.setId(Long.parseLong(vo.getId()));
        credentialHangService.updateByIdE(infoEntity);
        return R.ok();
    }

    @PostMapping("/unVaildCredentialHang")
    @ApiOperation("解除挂证")
    @SysAuthorityLog(value = "解除挂证")
    @Transactional
    public R unVaildCredentialHang(@RequestBody @Valid CredentialCheckVo vo,HttpServletRequest request)throws Exception{
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        CredentialHangEntity infoEntity = BeanUtilsMabach.doToDto(vo,CredentialHangEntity.class);
        infoEntity.setApplierCode(userInfo.getString("usercode"));
        CredentialHangEntity oldInfoEntity = credentialHangService.getByIdE(Long.parseLong(vo.getId()));
        if(ObjectUtils.isEmpty(oldInfoEntity)){
            return R.error("挂靠信息不存在，无法解除");
        }
        CredentialInfoEntity entity = credentialInfoService.getByIdE(oldInfoEntity.getCredentialId());
        infoEntity.setId(Long.parseLong(vo.getId()));
        if(ObjectUtils.isEmpty(entity)){
            return R.error("资质信息已被删除无法解除");
        }
        entity.setHangStatus(CredentialConst.HANG_STATUS_UNVAILD_CONFIRM);
        credentialInfoService.updateByIdE(entity);
        credentialHangService.updateByIdE(infoEntity);
        return R.ok();
    }


    @PostMapping("/saveOrUpdateCredentialItem")
    @ApiOperation("更新/插入资质子项")
    @SysAuthorityLog(value = "更新/插入资质子项")
    @Transactional
    public R saveOrUpdateCredentialItem(@RequestBody @Valid CredentialItemDto dto){
        credentialItemDao.deleteItem(1);
        credentialItemDao.deleteItem(2);
        credentialItemDao.deleteItem(3);
        for(CredentialItemEntity entity:dto.getJobSeries()){
                credentialItemService.saveE(entity);
        }

        for(CredentialItemEntity entity:dto.getCredentialLevel()){
            credentialItemService.saveE(entity);

        }

        for(CredentialItemEntity entity:dto.getProfession()){
                credentialItemService.saveE(entity);
        }
        return R.ok();
    }

    @PostMapping("/getCredentialItemList")
    @ApiOperation("获取配置子项")
    public R<CredentialItemDto> getCredentialItemList(){
        List<CredentialItemEntity> jobSeries = credentialItemDao.selectList(new QueryWrapper<CredentialItemEntity>().eq("type", CredentialConst.ITEM_JOB_SERIES).eq("is_delete",0));
        List<CredentialItemEntity> credentialLevel = credentialItemDao.selectList(new QueryWrapper<CredentialItemEntity>().eq("type", CredentialConst.ITEM_CREDENTIAL_LEVEL).eq("is_delete",0));
        List<CredentialItemEntity> profession = credentialItemDao.selectList(new QueryWrapper<CredentialItemEntity>().eq("type", CredentialConst.ITEM_PROFESSION).eq("is_delete",0));
        CredentialItemDto dto = new CredentialItemDto();
        dto.setJobSeries(jobSeries);
        dto.setCredentialLevel(credentialLevel);
        dto.setProfession(profession);
        return R.ok(dto);
    }


    @ApiOperation("修改员工资质信息")
    @PostMapping("/saveOrUpdateCredential")
    @Transactional
    public R saveOrUpdateCredential(@RequestBody @Valid CredentialInfoVo entity, HttpServletRequest request)throws Exception{
        CredentialInfoEntity infoEntity = BeanUtilsMabach.doToDto(entity,CredentialInfoEntity.class);
        infoEntity.setOid(entity.getOid());
        infoEntity.setUnitId(entity.getCompanyId());
        credentialInfoService.updateByIdE(infoEntity);
        return R.ok();
    }


}
